import {
  INCLUDE_TAG,
  EXCLUDE_TAG,
  END_TAG,
  isArray
} from '@shared';

const startSign = ',\\n(\\s+){\\n\\s+';
const endSign = '\\n\\s+}';
const includeText = `"${INCLUDE_TAG}":\\s"([A-Z\\d\\-\\|\\s]+)"`;
const excludeText = `"${EXCLUDE_TAG}":\\s"([A-Z\\d\\-\\|\\s]+)"`;
const leftEndText = ',\\s+{';
const endText = `"${END_TAG}":\\strue`;

const includePattern = new RegExp(startSign + includeText + endSign + leftEndText, 'g');
const excludePattern = new RegExp(startSign + excludeText + endSign + leftEndText, 'g');
const endifPattern = new RegExp(startSign + endText + endSign + '(,)?', 'g');

// 创建 uni-app 规范的条件编译注释
export function injectPlatforms(pagesJsonString) {
  pagesJsonString = pagesJsonString
    .replace(includePattern, '\n$1// #ifdef $2\n$1,\{')
    .replace(excludePattern, '\n$1// #ifndef $2\n$1,\{')
    .replace(endifPattern, '$2\n$1// #endif');

  return pagesJsonString;
}
// 条件编译信息转换为数组
export function formatPlatforms(value) {
  // 开发期间使用小写，更加方便。
  return value.toLowerCase().split('||');
}
// 条件编译信息转换为符合 uni-app 开发规范的字符串
export function serializePlatforms(value) {
  const valueText = isArray(value) ? value.join(' || ') : value;
  return valueText.toUpperCase();
}
